package com.chianghao.rockframewrok.auth.core.token.impl;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.fastjson.JSON;
import com.chianghao.rockframewrok.auth.core.token.ITokenCache;
import com.chianghao.rockframewrok.auth.core.token.model.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 
 * @author chiang
 *
 */
public class TokenCacheImpl implements ITokenCache {

	private static final ConcurrentHashMap<String, Token> tokenCache = new ConcurrentHashMap<String, Token>();
	
	Logger log  = LoggerFactory.getLogger(this.getClass());
	
	
	@Override
	public <T extends Token> void put(T token) {
		tokenCache.put(token.getId(), token);
	}

	@Override
	public <T extends Token> void remove(String id) {
		tokenCache.remove(id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <T extends Token> T get(String id) {
		return (T) tokenCache.get(id);
	}

	@Override
	public void cleanExpToken() {
		Thread cleanThread = new Thread(new CleanExpTokenThread());
		cleanThread.setName("清除过期token的线程");
		cleanThread.start();
	}
	
	class CleanExpTokenThread implements Runnable{

		@Override
		public void run() {
			while(true) {
				for(Entry<String,Token> entry:tokenCache.entrySet()) {
					String key = entry.getKey();
					Token  value = entry.getValue();
					if(value==null||value.getExpTime()==null){
						tokenCache.remove(key);
					}else{
						if(value.getExpTime()<System.currentTimeMillis()) {
							tokenCache.remove(key);
						}
					}
				}
				try {
					Thread.sleep(1);
				} catch (InterruptedException e) {
					log.error("[清理TOKEN中断]退出线程执行,异常信息为{}",e.getMessage());
					break;
				}
			}
		}
	}

	
}
